package com.resume.aipeople.service;

import com.resume.aipeople.dto.*;
import com.resume.aipeople.entity.User;
import com.resume.aipeople.repository.UserRepository;
import com.resume.aipeople.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
@RequiredArgsConstructor
@Slf4j
public class UserService implements UserDetailsService {
    
    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtils jwtUtils;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsernameOrEmail(username, username)
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在: " + username));
        
        return user;
    }
    
    @Transactional
    public AuthResponse register(RegisterRequest request) {
        try {
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(request.getUsername())) {
                return new AuthResponse("用户名已存在");
            }
            
            // 检查邮箱是否已存在
            if (userRepository.existsByEmail(request.getEmail())) {
                return new AuthResponse("邮箱已注册");
            }
            
            // 创建新用户
            User user = new User();
            user.setUsername(request.getUsername());
            user.setEmail(request.getEmail());
            user.setPassword(passwordEncoder.encode(request.getPassword()));
            user.setNickname(request.getNickname() != null ? request.getNickname() : request.getUsername());
            user.setRole(User.Role.USER);
            user.setIsActive(true);
            
            user = userRepository.save(user);
            log.info("新用户注册成功: {}", user.getUsername());
            
            // 生成JWT token
            String token = jwtUtils.generateToken(user.getUsername());
            
            return new AuthResponse(token, convertToUserDTO(user));
            
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return new AuthResponse("注册失败，请稍后再试");
        }
    }
    
    @Transactional
    public AuthResponse login(LoginRequest request) {
        try {
            // 查找用户
            Optional<User> userOpt = userRepository.findByUsernameOrEmail(
                    request.getUsernameOrEmail(), request.getUsernameOrEmail());
            if (!userOpt.isPresent()) {
                return new AuthResponse("用户名或密码错误");
            }
            User user = userOpt.get();
            
            // 校验密码
            if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
                return new AuthResponse("用户名或密码错误");
            }
            
            // 更新最后登录时间
            user.setLastLoginAt(LocalDateTime.now());
            userRepository.save(user);
            
            // 生成JWT token
            String token = jwtUtils.generateToken(user.getUsername());
            
            log.info("用户登录成功: {}", user.getUsername());
            return new AuthResponse(token, convertToUserDTO(user));
            
        } catch (Exception e) {
            log.error("用户登录失败: {}", request.getUsernameOrEmail(), e);
            return new AuthResponse("用户名或密码错误");
        }
    }
    
    public Optional<User> findByUsername(String username) {
        return userRepository.findByUsername(username);
    }
    
    public Optional<User> findById(Long id) {
        return userRepository.findById(id);
    }
    
    private UserDTO convertToUserDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUsername(user.getUsername());
        dto.setEmail(user.getEmail());
        dto.setNickname(user.getNickname());
        dto.setAvatarUrl(user.getAvatarUrl());
        dto.setRole(user.getRole().name());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setLastLoginAt(user.getLastLoginAt());
        return dto;
    }
}
